package com.office.automate.servlet.administration;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.office.automate.dto.convertors.AdministrationDetailConvertor;
import com.office.automate.exception.framework.FrontierVisibleException;
import com.office.automate.model.administration.Division;
import com.office.automate.service.def.administration.AdministrationService;
import com.office.automate.service.impl.administration.AdministrationServiceImplementer;
import com.office.automate.validation.framework.ValidatorObject;

/**
 * Servlet implementation class ManageDivisionsServlet
 */
@WebServlet("/ManageDivisionsServlet")
public class ManageDivisionsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManageDivisionsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/administration/ManageDivisions.jsp");
		try {
			AdministrationService administrationService = new AdministrationServiceImplementer();
			Division division = new AdministrationDetailConvertor().convertAddDivisionDetailRequest(request);
			HashMap<String, FrontierVisibleException> fieldValidationErrors = 
												administrationService.validateDivisionDetails(division);
			if (fieldValidationErrors != null) {
				request.setAttribute("Division", division);
				request.setAttribute("FieldValidationErrors", new ValidatorObject(fieldValidationErrors));
				dispatcher.forward(request, response);		
			} else {
				division = administrationService.addDivision(division);
				request.setAttribute("New_Division", division);
				dispatcher.forward(request, response);				
			}
		} catch (FrontierVisibleException e) {
			request.setAttribute("OperationalError", e);
			dispatcher.forward(request, response);	
		}
	}
}
